import { Button, Checkbox, Form, Input, message, Modal, Select } from "antd";
import { XIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { apiRolesList } from "~/api";
import { apiAddUserAuthor } from "~/api/author";
import Title from "~/components/ui/title";
import type { IUserAuthor } from "~/types/manage/content/author";
import type { IRole } from "~/types/manage/system/role";

interface Props {
  visible: boolean;
  userAuthor?: IUserAuthor | null;
  onCancel?: () => void;
  onOk?: () => void;
}

export default function UserAuthorModal(props: Props) {
  const [form] = Form.useForm();
  const [roleList, setRoleList] = useState<IRole[]>([]);

  const _handler = {
    onCancel: () => {
      props.onCancel?.();
    },
    onOk: async (type: "add" | "edit") => {
      try {
        await form.validateFields();
        const fieldsValue: IUserAuthor = form.getFieldsValue(true);
        if (!fieldsValue.authors || fieldsValue.authors.length === 0) {
          message.error("请添加作者笔名信息");
          return;
        }
        if (!fieldsValue.authors.some((item) => item.isDefault)) {
          message.error("请设置作者默认笔名");
          return;
        }
        const data: IUserAuthor = {
          ...fieldsValue,
        };
        await apiAddUserAuthor(data);
        props.onOk?.();

        message.success(type === "edit" ? "编辑成功" : "新增成功");
      } catch (error: any) {}
    },
  };

  const _fetch = {
    init: async () => {
      const roleListResp = await apiRolesList();
      setRoleList(roleListResp);
    },
  };

  useEffect(() => {
    if (!props.visible) {
      return;
    }
    form.resetFields();
    if (props.userAuthor) {
      form.setFieldsValue(props.userAuthor);
    }
  }, [props.userAuthor, props.visible, form]);

  useEffect(() => {
    _fetch.init();
  }, []);

  return (
    <Modal
      title={props.userAuthor?.id ? "编辑作者" : "添加作者"}
      open={props.visible}
      maskClosable={false}
      onCancel={_handler.onCancel}
      onOk={() => {
        _handler.onOk(props.userAuthor ? "edit" : "add");
      }}
      width={800}
    >
      <Form
        form={form}
        className="rp-[.ant-form-item]:!mb-0"
        initialValues={{
          authors: [{}],
        }}
      >
        <Title title="账号信息" />
        <div className="my-2 grid grid-cols-3 gap-4 rounded p-4">
          <Form.Item
            label={"用户名"}
            name={"username"}
            rules={[{ message: "请输入用户名" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={"账号"}
            name={"account"}
            rules={[{ message: "请输入账号" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={"邮箱"}
            name={"email"}
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入有效的邮箱地址" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={"手机号"}
            name={"mobile"}
            rules={[
              { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item label={"角色"} name={"roleIds"} className="col-span-2">
            <Select
              mode="multiple"
              options={roleList.map((item) => {
                return {
                  label: item.name,
                  value: item.id,
                };
              })}
            />
          </Form.Item>
        </div>
        <Title title="基本信息" />
        <Form.List name={"authors"}>
          {(fields, { add, remove }) => (
            <>
              <div className="my-2 flex flex-col gap-4 rounded p-4">
                {fields.map((item) => (
                  <div className="flex gap-2" key={item.key}>
                    <div className="grid flex-1 grid-cols-6 gap-4">
                      <Form.Item
                        label={"笔名"}
                        name={[item.name, "penName"]}
                        rules={[{ required: true, message: "请输入笔名" }]}
                        className="col-span-2"
                      >
                        <Input placeholder="笔名" />
                      </Form.Item>
                      <Form.Item
                        label={"默认"}
                        name={[item.name, "isDefault"]}
                        valuePropName="checked"
                      >
                        <Checkbox
                          onChange={(checked) => {
                            if (checked) {
                              const authors = form.getFieldValue("authors");
                              const index = item.key;
                              form.setFieldValue(
                                "authors",
                                authors.map((item: any, i: number) => {
                                  if (i === index) {
                                    return {
                                      ...item,
                                      isDefault: true,
                                    };
                                  }
                                  return {
                                    ...item,
                                    isDefault: false,
                                  };
                                }),
                              );
                            }
                          }}
                        />
                      </Form.Item>
                    </div>

                    <div
                      className="flex w-8 items-center justify-center rounded hover:bg-gray-200"
                      onClick={() => remove(item.name)}
                    >
                      <XIcon size={18} />
                    </div>
                  </div>
                ))}
                <Button type="dashed" onClick={() => add()} block>
                  添加笔名
                </Button>
              </div>
            </>
          )}
        </Form.List>
        <Title title="实名信息" />
        <div className="my-2 grid grid-cols-3 gap-x-4 rounded p-4">
          <Form.Item
            label={"姓名"}
            name={["real", "realName"]}
            rules={[{ message: "请输入真实姓名" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={"身份证号"}
            name={["real", "idCard"]}
            className="col-span-2"
            rules={[
              { message: "请输入身份证号" },
              {
                pattern:
                  /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
                message: "请输入有效的身份证号",
              },
            ]}
          >
            <Input />
          </Form.Item>
        </div>
        <Title title="收款信息" />
        <Form.List name={"payments"}>
          {(fields, { add, remove }) => (
            <>
              <div className="my-2 flex flex-col gap-4 rounded p-4">
                {fields.map((item) => (
                  <div className="flex gap-2" key={item.key}>
                    <div className="grid flex-1 grid-cols-6 gap-4">
                      <Form.Item
                        label={""}
                        name={[item.name, "type"]}
                        rules={[{ required: true, message: "请选择收款渠道" }]}
                      >
                        <Select
                          options={[
                            {
                              label: "支付宝",
                              value: 1,
                            },
                            {
                              label: "微信",
                              value: 2,
                            },
                            {
                              label: "银行卡",
                              value: 3,
                            },
                          ]}
                        />
                      </Form.Item>
                      <Form.Item
                        label={"账号"}
                        name={[item.name, "account"]}
                        rules={[{ required: true, message: "请输入收款账号" }]}
                        className="col-span-2"
                      >
                        <Input placeholder="账号" />
                      </Form.Item>
                      <Form.Item
                        label={"支行"}
                        name={[item.name, "bankName"]}
                        className="col-span-2"
                      >
                        <Input placeholder="银行支行" />
                      </Form.Item>
                      <Form.Item
                        label={"默认"}
                        name={[item.name, "isDefault"]}
                        valuePropName="checked"
                      >
                        <Checkbox
                          onChange={(checked) => {
                            if (checked) {
                              const payments = form.getFieldValue("payments");
                              const index = item.key;
                              form.setFieldValue(
                                "payments",
                                payments.map((item: any, i: number) => {
                                  if (i === index) {
                                    return {
                                      ...item,
                                      isDefault: true,
                                    };
                                  }
                                  return {
                                    ...item,
                                    isDefault: false,
                                  };
                                }),
                              );
                            }
                          }}
                        />
                      </Form.Item>
                    </div>

                    <div
                      className="flex w-8 items-center justify-center rounded hover:bg-gray-200"
                      onClick={() => remove(item.name)}
                    >
                      <XIcon size={18} />
                    </div>
                  </div>
                ))}
                <Button type="dashed" onClick={() => add()} block>
                  添加收款方式
                </Button>
              </div>
            </>
          )}
        </Form.List>
      </Form>
    </Modal>
  );
}
